package com.tju.Service;

import com.tju.Util.ResultDO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import javax.annotation.Resource;
import java.util.*;

/**
 * 一个自定义的service用来和数据库进行操作. 即以后我们要通过数据库保存权限.则需要我们继承UserDetailsService
 *
 * @author liukai
 */
@Slf4j
public class CustomUserDetailsService implements UserDetailsService {

    @Resource
    private UserService userServiceImpl;

    @Resource
    private UserRoleService userRoleServiceImpl;

    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        System.out.println("username is " + username);
        com.tju.Model.User loginUser = this.userServiceImpl.selectLogin(username);
        if(loginUser == null) {
            throw new UsernameNotFoundException("用户名不存在");
        }
        if(loginUser.getUserFlag()==0)
        {
            throw new UsernameNotFoundException("用户尚未激活，请联系管理员");
        }

        Collection<GrantedAuthority> grantedAuths = obtionGrantedAuthorities(loginUser);

        boolean enables = true;
        boolean accountNonExpired = true;
        boolean credentialsNonExpired = true;
        boolean accountNonLocked = true;

        User userdetail = new User(loginUser.getUserName(), loginUser.getUserPwd(), enables, accountNonExpired, credentialsNonExpired, accountNonLocked, grantedAuths);
        return userdetail;
    }

    //取得用户的权限
    private Set<GrantedAuthority> obtionGrantedAuthorities(com.tju.Model.User user) {

        Set<GrantedAuthority> authSet = new HashSet<GrantedAuthority>();
        ResultDO<List<String>> userRolesListResult = userRoleServiceImpl.getUserRolesByUserId(user.getUserId());
        if(userRolesListResult.isSuccess())
        {
            /**
             * 为防止意外 此处还是去重下比较好
             */
            List<String> userRolesList = new ArrayList<>(new HashSet<>(userRolesListResult.getModule()));
            for(String roleName : userRolesList) {
                    authSet.add(new SimpleGrantedAuthority(roleName));
            }
            return authSet;
        }else{
            log.error("error:获取用户权限失败");
            return  null;
        }
    }
}
